<?php

namespace app\admin\controller\evaluation;

use app\admin\model\EvaluationElist;
use app\admin\model\EvaluationQrcode;
use app\admin\model\EvaluationTemplate;
use app\admin\model\SystemAdmin;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use think\Request;
use jianyan\excel\Excel;
/**
 * @ControllerAnnotation(title="evaluation_qrcode")
 */
class Qrcode extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\EvaluationQrcode();
        
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model->with(['evaluationTemplate','systemAdmin'])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {
        if ($this->request->isPost()) {

            $this->checkPostRequest();

            $Excel = new \jianyan\excel\Excel;

            $post = $this->request->post();

            $file = explode('upload',$post['logo']);
            $array = $Excel->import(ROOT_PATH."public/upload".$file[1],2);
            Db::startTrans();
            foreach ($array as $key=>$val){

                if($key==0) continue;

                $post = [];
                $template_id = EvaluationTemplate::where('name',trim($val[0]))->value('id');
                if(!$template_id){
                    // 回滚事务
                    Db::rollback();
                    $this->error('模板名称为：' . $val[0] . ',的模板不存在');
                }
                $post['template_id'] = $template_id;
                $post['class_name'] =$val[1];
                $post['class_desc'] =$val[2];
                $class_start_time = date('Y-m-d H:i:s',strtotime($val[3]));

                $class_end_time = date('Y-m-d H:i:s',strtotime($val[4]));
                $post['class_time'] = $class_start_time . ' - ' . $class_end_time;

                $evaluate_start_time = date('Y-m-d',strtotime($val[5]));

                $evaluate_end_time = date('Y-m-d',strtotime($val[6]));

                $post['evaluate_period_time'] = $evaluate_start_time . ' - ' . $evaluate_end_time;
                $post['is_check'] = $val[7] == '是' ? 1 : 0;
                $post['student_arr'] = explode(',',$val[8]);
                $post['qr_user_id'] =  session('admin.id');
                $post['qr_source'] = 3;//文件导入
                $post['create_time'] = time();
                $post['update_time'] = time();
                $qr_id = $this->model->insertGetId($post);
                if(!$qr_id){
                    Db::rollback();
                    $this->error('导入失败');
                }
                $content = '班级名称:' .$post['class_name']. PHP_EOL .'班级描述：' . $post['class_desc'] . PHP_EOL . '上课时间：' .$post['class_time']. PHP_EOL. '截至时间：' .$post['evaluate_period_time'];
                list($qr_code,$value) = getCode($post['template_id'],$qr_id,$content);

                $up_post['qr_code'] = $qr_code;
                $up_post['link_address'] = $value;

                $save = $this->model->where('id',$qr_id)->update($up_post);

                if(!$save){
                    Db::rollback();
                    $this->error('导入失败');
                }

            }
            Db::commit();
            $this->success('导入成功');

        }

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export(Request $request)
    {
        $this->relationSearch = true;
        list($page, $limit, $where) = $this->buildTableParames();

        $header = [
            ['模板名称','template_name'],
            ['班级名称','class_name'],
            ['班级描述','class_desc'],
            ['上课开始时间','class_start_time'],
            ['上课结束时间','class_end_time'],
            ['评价开始时间','evaluate_start_time'],
            ['评价开始时间','evaluate_end_time'],
            ['姓名校验','is_check'],
            ['学生姓名','student_arr'],
            ['生成人','qr_user_name'],
            ['创建时间','create_time'],
            ['数据来源','qr_source'],
            ['总人数','total_nums'],
            ['已评人数','y_nums'],
            ['待评人数','d_nums'],
            ['未评人','no_eval_name'],
        ];
        $list = $this->model->where($where)->order('id','desc')->select()->toArray();


        foreach($list as &$v){
            $student_arr = $v['student_arr'];
            $v['template_name']       = EvaluationTemplate::where('id',$v['template_id'])->value('name');
            $v['class_start_time']    = explode(' - ', $v['class_time'])[0];
            $v['class_end_time']      = explode(' - ', $v['class_time'])[1];
            $v['evaluate_start_time'] = explode(' - ', $v['evaluate_period_time'])[0];
            $v['evaluate_end_time']   = explode(' - ', $v['evaluate_period_time'])[1];
            $v['is_check']            = $v['is_check'] ? '是' : '否';
            $v['student_arr']         = implode(',',$student_arr);
            $v['qr_user_name']        = SystemAdmin::where('id',$v['qr_user_id'])->value('username');
            if($v['qr_source'] == 1){
                $v['qr_source'] = '手动输入';
            }elseif($v['qr_source'] == 2){
                $v['qr_source'] = 'API传递';
            }elseif($v['qr_source'] == 3){
                $v['qr_source'] = '文件上传';
            }
            $v['total_nums']          = count($student_arr);
            $v['y_nums']                = EvaluationElist::where('qr_id',$v['id'])->group('student_name')->count();
            $v['d_nums']                = $v['total_nums']  - $v['y_nums'];

            $yes_student_name = EvaluationElist::where('qr_id',$v['id'])->group('student_name')->column('student_name');
            foreach($yes_student_name as $vv){
                $key = array_search($vv,$student_arr);
                if($key >= 0){
                    unset($student_arr[$key]);
                }
            }
            $v['no_eval_name'] = implode(',',$student_arr);


        }
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
    
}